package com.fit.pages.manufacturer;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.manufacturer.ManufacturerDAO;
import com.fit.dao.user.UserDAO;
import com.fit.dao.wholesale.WholesaleDAO;
import com.fit.entities.Manufacturer;
import com.fit.entities.Wholesale;
import com.fit.model.glov.GenericSelectModel;
import com.fit.model.user.MD5;

@AdminAccess
public class EditManufacturer {

	@Property
	@Persist
	private Manufacturer manufacturer;

	@Inject
	private ManufacturerDAO manufacturerDAO;

	@Component
	private Form editForm;

	@InjectPage
	private ManageManufacturers manage;

//	@Property
//	@Persist
//	private UserType userType;

	@Inject
	private WholesaleDAO wholesaleDAO;

	private GenericSelectModel<Wholesale> wholesales;

	@Property
	private Wholesale wholesale;

	@Inject
	private PropertyAccess access;
	
	@Inject
	private Messages messages;

	public GenericSelectModel<Wholesale> getWholesales() {
		wholesales = new GenericSelectModel<Wholesale>(wholesaleDAO.findAll(),
				Wholesale.class, "name", "name", access);
		return wholesales;
	}

//	public SelectModel getTypes() {
//		return new EnumSelectModel(UserType.class, messages);
//	}

	Object onActivate(Long id) {
		manage.setError("");
		manage.setConfirmation("");
		Manufacturer m = manufacturerDAO.findById(id);
		if (m != null) {
			manufacturer = m;
		}
		if (manufacturer == null) {
			manage.setError("Error");
			return manage;
		}
		return null;
	}

	Object onSubmitFromEditForm() {
		manage.setError("");
		manage.setConfirmation("");
		try {
			if (wholesale !=null && manufacturer.getWholesale() != wholesale) {
				manufacturer.setWholesale(wholesale);
			}
			manufacturerDAO.update(manufacturer);
			manage.setConfirmation("Successfully edited.");
			return manage;
		} catch (Exception e) {
			manage.setError("Error.");
			return manage;
		}
	}
	
	public boolean isWholesaleNotNull(){
		if(manufacturer.getWholesale()!=null){
			return true;
		}
		return false;
	}
	
	@OnEvent(component = "removeWholesaleLink")
	Object onRemoveWholesaleLink() {
		manufacturer.setWholesale(null);
		return null;
	}

}
